package com.hd.crdao.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hd.crdao.R;
import com.hd.crdao.proxy.BitmapThreadPool;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.GlobalData;
import com.hd.crdao.utils.MyToast;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class TakeCameraActivity extends Activity implements SurfaceHolder.Callback, View.OnClickListener {
    private static final int GET_PHOTO_DATA = 100;
    private static final int SAVE_CAMERAPHOTO_SUCCESS = 120;
    public Camera mCamera;

    public SurfaceView mSurfaceView;
    public SurfaceHolder holder;
    public AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback();
    public Button tv_save, tv_cancle;
    public TextView mTvDesc;
    private int i = 0;
    private HandlerThread mHandlerThread;
    private Handler mHandlerJpeg;
    public ArrayList<String> imagePaths = new ArrayList<>();
    public int curPosition;
    public ImageView mTakePicture;
    public View mProView;
    public ArrayList<String> mainImagePaths;
    public List<Integer> finalIndexList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_takecamera);
        /*intent.putStringArrayListExtra("imagePaths", imagePaths);       //如果能够进入拍照界面,集合的长度一定为12
        intent.putExtra("curPosition", position);       //点击的是哪一张默认图片*/
        mainImagePaths = getIntent().getStringArrayListExtra("imagePaths");
        curPosition = getIntent().getIntExtra("curPosition", 0);
        getFinalIndexList();
        initHandlerThread();
        initView();
        initListener();
        initData();


    }

    /**
     * 获取到最终的空的索引集合
     */
    private List<Integer> getFinalIndexList() {
        ArrayList<Integer> list = reCountIsEmpty(mainImagePaths);   //统计从上传图片过来所有空的位置
        for (int j = 0; j < list.size(); j++) {
            if (curPosition == list.get(j)) {
                list.remove(j);
            }
        }
        return list;
    }

    /**
     * 重新统计集合中哪些是空的数据的索引集合
     *
     * @return
     */
    private ArrayList<Integer> reCountIsEmpty(ArrayList<String> targetList) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < targetList.size(); i++) {
            if (TextUtils.isEmpty(targetList.get(i))) {
                list.add(i);
            }
        }
        return list;
    }


    public void initView() {
        tv_save = (Button) findViewById(R.id.tv_save);
        tv_cancle = (Button) findViewById(R.id.tv_cancle);
        mSurfaceView = (SurfaceView) findViewById(R.id.mSurfaceView);
        mTakePicture = (ImageView) findViewById(R.id.mybutton);
        mTvDesc = (TextView) findViewById(R.id.tvPicDesc);
        mProView = findViewById(R.id.proView);
    }


    public void initData() {
        if (imagePaths.isEmpty()) {
            tv_save.setEnabled(false);
            tv_save.setTextColor(Color.parseColor("#666666"));
        }
        holder = mSurfaceView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        upDateDesc(curPosition);       //更新上传图片的位置和图片的描述
        finalIndexList = getFinalIndexList();
    }

    public void initListener() {
        tv_cancle.setOnClickListener(this);
        tv_save.setOnClickListener(this);
        mSurfaceView.setOnClickListener(this);
        mTakePicture.setOnClickListener(this);
    }


    @Override
    public void surfaceCreated(SurfaceHolder surfaceholder) {
        try {
            /* 打开相机， */
            ALog.d("打开照相功能！");
            mCamera = Camera.open();
            mCamera.startPreview();
            mCamera.setPreviewDisplay(holder);
        } catch (Exception e) {
            ALog.d(e.getMessage());
            Toast.makeText(this, "打开相机失败，请查看系统设置中相机权限是否开启", Toast.LENGTH_SHORT).show();
            if (mCamera != null) {
                mCamera.release();
                mCamera = null;
            }

        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceholder, int format, int w, int h) {
        /* 相机初始化 */
        initCamera();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceholder) {
        stopCamera();
        if (mCamera != null) {
            mCamera.release();
        }
        mCamera = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCamera != null) {
            stopCamera();
            if (mCamera != null) {
                mCamera.release();
            }
            mCamera = null;
        }
    }


    public PictureCallback jpegCallback = new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            Message message = Message.obtain();
            message.what = GET_PHOTO_DATA;
            message.obj = data;
            mHandlerJpeg.sendMessage(message);

        }
    };

    public void initHandlerThread() {
        mHandlerThread = new HandlerThread("Test");
        mHandlerThread.start();

        mHandlerJpeg = new Handler(mHandlerThread.getLooper(), new Handler.Callback() {

            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == GET_PHOTO_DATA) {
                    final byte[] data = (byte[]) msg.obj;

                    BitmapThreadPool.post(new Runnable() {
                        @Override
                        public void run() {
                            // do everything
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {

                                        // 把摄像头获得画面显示在SurfaceView控件里面
                                        mCamera.setPreviewDisplay(mSurfaceView.getHolder());
                                        mCamera.setDisplayOrientation(90);
                                        mCamera.startPreview();// 开始预览
                                        mProView.setVisibility(View.GONE);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                            saveImage(data);
                        }
                    });
                }
                return true;
            }
        });

    }


    /**
     * 设置预览的大小
     *
     * @param parameters
     * @param sizeList
     * @param position
     * @return
     */

    public boolean setPreviewSize(Camera.Parameters parameters, List<Camera.Size> sizeList, int position) {
        int PreviewWidth;
        int PreviewHeight;

        PreviewWidth = sizeList.get(position).width;
        PreviewHeight = sizeList.get(position).height;

        try {
            if (PreviewWidth > 1400) {
                return false;
            }
            parameters.setPreviewSize(PreviewWidth, PreviewHeight);
            // //获得摄像区域的大小
            parameters.setPictureFormat(ImageFormat.JPEG);// 设置照片输出的格式
            parameters.setJpegQuality(100);// 设置照片质量

            parameters.setPictureSize(PreviewWidth, PreviewHeight);// 设置拍出来的屏幕大小

            mCamera.setParameters(parameters);// 把上面的设置 赋给摄像头
            mCamera.setPreviewDisplay(mSurfaceView.getHolder());// 把摄像头获得画面显示在SurfaceView控件里面
            mCamera.setDisplayOrientation(90);
            mCamera.startPreview();// 开始预览
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public void getCameraSize(Camera.Parameters parameters, List<Camera.Size> sizeList, boolean sort) {
        int position;
        if (sort) {
            position = i;
        } else {
            position = sizeList.size() - i - 1;
        }
        if (!setPreviewSize(parameters, sizeList, position)) {
            i++;
            getCameraSize(parameters, sizeList, sort);
        }
    }

    /**
     * 调整角度/压缩操作
     *
     * @param bm
     * @param orientationDegree
     * @return
     */
    private Bitmap adjustPhotoRotation(Bitmap bm, final int orientationDegree) {

        Matrix m = new Matrix();
        m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
        float targetX, targetY;
        if (orientationDegree == 90) {
            targetX = bm.getHeight();
            targetY = 0;
        } else {
            targetX = bm.getHeight();
            targetY = bm.getWidth();
        }

        final float[] values = new float[9];
        m.getValues(values);

        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];

        m.postTranslate(targetX - x1, targetY - y1);
        //进行压缩操作
        Bitmap targetBitmap = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(), Bitmap.Config.ARGB_8888);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(targetBitmap);
        canvas.drawBitmap(bm, m, paint);
        return targetBitmap;
    }

    private int count = 0;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_cancle:
                finish();
                break;
            case R.id.tv_save:
                savePaths();
                break;
            case R.id.mSurfaceView:
                try {
                    mCamera.autoFocus(mAutoFocusCallback);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.mybutton:
                if (imagePaths.size() >= reCountIsEmpty(mainImagePaths).size()) {
                    MyToast.show("已达到最大数量哦~~!");
                    break;
                }
                if (mProView.getVisibility() == View.GONE) {
                    mProView.setVisibility(View.VISIBLE);
                    takePicture();
                    ALog.d("当前值是:" + count + "");
                    try {
                        upDateDesc(finalIndexList.get(count));
                       /* if (imagePaths.size() == 1) {
                            count = 0;
                        }*/
                    } catch (IndexOutOfBoundsException e) {
                        ALog.d(e.getMessage());
                    }
                    count++;
                }


                break;
            default:
                break;
        }
    }

    private void savePaths() {
        Intent intent = new Intent();
        intent.putStringArrayListExtra("imagePaths", imagePaths);
        setResult(SAVE_CAMERAPHOTO_SUCCESS, intent);
        finish();
    }

    /**
     * 拍照的方法
     */
    private void takePicture() {
        ALog.d("相机被调用");

        if (mCamera != null) {
            mCamera.takePicture(null, null, jpegCallback);

        }
    }


    /* 告定义class AutoFocusCallback */
    private final class AutoFocusCallback implements Camera.AutoFocusCallback {
        @Override
        public void onAutoFocus(boolean focused, Camera camera) {

        }
    }

    /* 相机初始化的method */
    private void initCamera() {
        if (mCamera != null) {
            Camera.Parameters parameters = mCamera.getParameters();
            List<Camera.Size> sizeList = parameters.getSupportedPreviewSizes();

            boolean flag = false;
            // 如果sizeList只有一个我们也没有必要做什么了，因为就他一个别无选择
            if (sizeList.size() > 0) {

                for (int i = 0; i < sizeList.size(); i++) {

                    if (i != 0 && sizeList.get(0).width > sizeList.get(i).width) {
                        flag = true;// 从大到小
                        break;
                    }
                }
                getCameraSize(parameters, sizeList, flag);
            } else {
                MyToast.show("无法连接相机,请检查相机是否被占用!");
            }

        }
    }

    /* 停止相机的method */
    private void stopCamera() {
        if (mCamera != null) {
            try {
                /* 停止预览 */
                mCamera.stopPreview();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Bitmap对象保存味图片文件
     *
     * @param bitmap
     */
    public String saveBitmapFile(Bitmap bitmap) {
        File file = new File(GlobalData.tempImagePaht + "/" + System.currentTimeMillis() + ".jpg");
        if (!file.exists()) {
            try {
                if (!new File(GlobalData.tempImagePaht).exists()) {
                    new File(GlobalData.tempImagePaht).mkdirs();
                }
                file.createNewFile();
            } catch (IOException e) {
                ALog.d(e.getMessage());
            }
        }
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }


    public void saveImage(byte[] data) {
        try {
            if (data != null && data.length > 0) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize=1;
              //  options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                Bitmap bm = adjustPhotoRotation(BitmapFactory.decodeByteArray(data, 0, data.length,options), 90);
                String imagePath = saveBitmapFile(bm);
                imagePaths.add(imagePath);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_save.setEnabled(true);
                        tv_save.setTextColor(Color.WHITE);
                    }
                });
            }

        } catch (Exception e) {
            ALog.d(e.getMessage());
        }
    }


    public void upDateDesc(int changePosition) {
        String[] array = getResources().getStringArray(R.array.carPicturesDesc);
        if (changePosition < array.length) {
            mTvDesc.setText(array[changePosition] + "[" + (changePosition + 1) + "/12]");
        }
    }
}